package com.learning.javaweb_servlet_jdbcdbutils;


import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtilsTest {
    //设置基础数据，链接数据库
    static final String URL = "jdbc:mysql://localhost:3306/jdbc_demo?useSSL=true&serverTimezone=GMT&characterEncoding=UTF-8";
    static final String USER = "root";
    static final String PASSWORD = "WQ9ABCAT";


    //插入语句
    static final String INSERTRESULT="INSERT INTO student (name, age, gender) VALUES (?, ?, ?)";

    public static void main(String[] args)  {
        //建立对象，为后面接受数据库的链接做准备
        Connection conn = null;
        try {
            //链接数据库并接收
            conn= DriverManager.getConnection(URL,USER,PASSWORD);
            //保证事务同步，把自动提交先关掉
            conn.setAutoCommit(false);

            //创建查询对象
            QueryRunner queryRunner= new QueryRunner();

            //插入
            int insertResult = queryRunner.update(conn, INSERTRESULT, "老天师", 80, "男");
            System.out.println("Inserted " + insertResult + " row(s)");

            // Commit transaction and close connection
            DbUtils.commitAndClose(conn);
        }  catch (SQLException sqlException) {
            sqlException.printStackTrace();
            DbUtils.rollbackAndCloseQuietly(conn); // Rollback transaction and close connection quietly
        } catch (Exception e) {
            e.printStackTrace();
            DbUtils.closeQuietly(conn); // Close connection quietly
        }
    }

}